#!/bin/bash
# "Copyright [2023] <fisco-bcos>"
# @ function: check code format of {.h, .hpp and .cpp} files before commit
# @ require : Make sure your machine is UNIX, clang-format is ready
# @ author  : kyonRay
# @ file    : pre-commit
# @ date    : 2023

SHELL_FOLDER=$(
  cd $(dirname $0)
  pwd
)

check_script="clang-format"
commit_limit=1000
file_limit=35
insert_limit=300
license_line=20

skip_check_words="sync code|release"

LOG_ERROR() {
  content=${1}
  echo -e "\033[31m"${content}"\033[0m"
}

LOG_INFO() {
  content=${1}
  echo -e "\033[32m"${content}"\033[0m"
}

execute_cmd() {
  command="${1}"
  eval ${command}
  ret=$?
  if [ $ret -ne 0 ]; then
    LOG_ERROR "FAILED of command: ${command}"
    exit 1
  else
    LOG_INFO "SUCCESS of command: ${command}"
  fi
}

function check_codeFormat() {
  # if clang-format command not exist, print log and return directly
  if ! command -v ${check_script} &>/dev/null; then
    LOG_INFO "clang-format command not found, please install it, skip by default."
    exit 0
  fi
  # if clang-format first version less than 15 skip check
  if [ $(clang-format --version | awk '{print $3}' | awk -F '.' '{print $1}') -lt 15 ]; then
    LOG_INFO "clang-format version less than 15, skip check."
    exit 0
  fi
  # Redirect output to stderr.
  exec 1>&2
  sum=0
  for file in $(git diff-index --name-status HEAD -- | grep -v D | grep -E '\.[ch](pp)?$' | awk '{print $2}'); do
    clang-format -style=file -i $file --dry-run --Werror
    sum=$(expr ${sum} + $?)
    execute_cmd "$check_script -style=file -i $file"
  done

  if [ ${sum} -ne 0 ]; then
    echo "######### ERROR: Format check failed, please adjust them before commit"
    exit 1
  fi
}
check_codeFormat
